<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <!--友情提示-->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>

      <!--商品分类区域-->
      <el-row>
        <el-col :span="24">
          <span>选择商品分类：</span>
          <el-cascader
            expand-trigger="hover"
            :options="categoriesList"
            v-model="selectedCategories"
            @change="handleChange"
            :props="categoriesListProps"
          ></el-cascader>
        </el-col>
      </el-row>

      <!--标签切换-->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <el-table :data="manyTableData" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag+''+Math.random()"
                  v-for="(tag,i) in scope.row.attr_vals"
                  :disable-transitions="true"
                  closable
                  @close="tagClosed(scope.row,i)"
                >{{tag}}</el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  icon="el-icon-edit"
                  size="mini"
                >编辑</el-button>
                <el-button
                  type="danger"
                  @click="delParams(scope.row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isDisabled"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <el-table :data="onlyTableData" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="tag+''+Math.random()"
                  v-for="tag in scope.row.attr_vals"
                  :disable-transitions="true"
                  closable
                  @close="tagClosed(scope.row,i)"
                >{{tag}}</el-tag>

                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="showEditDialog(scope.row)"
                  icon="el-icon-edit"
                  size="mini"
                >编辑</el-button>
                <el-button
                  type="danger"
                  @click="delParams(scope.row.attr_id)"
                  icon="el-icon-delete"
                  size="mini"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!--添加参数弹框-->
      <el-dialog
        :title="'添加'+(activeName==='many'?'动态参数':'静态属性')"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addDialogclosed"
      >
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>

      <!--修改参数弹框-->
      <el-dialog
        :title="'修改'+(activeName==='many'?'动态参数':'静态属性')"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="editDialogclosed"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 供选取的三级分类信息
      categoriesList: [],
      // 选中后的三级分类信息
      selectedCategories: [],
      // 级联下拉列表属性定义
      categoriesListProps: {
        value: 'cat_id',
        label: 'cat_name'
      },

      // 标签切换
      activeName: 'many',
      // 动态参数 / 静态属性
      manyTableData: [],
      onlyTableData: [],

      /** 添加参数弹框/form表单部分1 */
      addDialogVisible: false,
      addForm: {
        // 参数名称
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入参数名称',
            trigger: 'blur'
          }
        ]
      },
      /** 添加参数弹框/form表单部分2 */

      /** 修改参数弹框/form表单部分1 */
      // 默认不展示弹框
      editDialogVisible: false,
      // form表单数据
      editForm: {
        // 参数名称
        attr_name: ''
      },
      // form表单校验对象
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      /** 修改参数弹框/form表单部分2 */

      /** 参数可选项1 */
      // 按钮 和 输入框 谁显示控制
      inputVisible: false,
      // 输入框 的设定值
      inputValue: ''
      /** 参数可选项2 */
    }
  },
  created() {
    // 获取供选取的三级分类数据
    this.getCategoriesList()
  },
  // 计算属性
  computed: {
    // 只有选取了第三级别分类，按钮才处于激活状态
    isDisabled: function() {
      if (this.selectedCategories.length === 3) {
        return false
      }
      return true
    },
    // 灵活获取第三级别分类的id信息
    catId() {
      if (this.selectedCategories.length === 3) {
        return this.selectedCategories[2]
      }
      return 0
    }
  },
  methods: {
    /** 参数可选项1 */
    // 删除操作
    async tagClosed(nowParam, index) {
      nowParam.attr_vals.splice(index, 1)

      // 通过 空格 拼接所有的可选项
      const attrVals = nowParam.attr_vals.join(' ')
      // 调用axios把可选项 信息提交给服务器保存
      const { data: res } = await this.$http.put(
        `categories/${nowParam.cat_id}/attributes/${nowParam.attr_id}`,
        {
          attr_name: nowParam.attr_name,
          attr_sel: nowParam.attr_sel,
          attr_vals: attrVals
        }
      )
      if (res.meta.status !== 200) {
        return this.$message({
          message: '删除可选项失败',
          type: 'error',
          duration: 1500
        })
      }
    },

    // 输入框失去焦点 或 敲回车 的回调处理
    async handleInputConfirm(nowParam) {
      // 如果用户没有设置可选项信息，就直接隐藏输入框并返回
      if (this.inputValue.trim().length === 0) {
        this.inputValue = ''
        this.inputVisible = false
        return null
      }
      // console.log(123)
      // 把数据追加给 参数的attr_vals属性中
      nowParam.attr_vals.push(this.inputValue.trim())
      // 清空当前输入的标签内容
      this.inputValue = ''
      // 隐藏输入框，显示按钮
      this.inputVisible = false

      // 通过 空格 拼接所有的可选项
      const attrVals = nowParam.attr_vals.join(' ')
      // 调用axios把可选项 信息提交给服务器保存
      const { data: res } = await this.$http.put(
        `categories/${nowParam.cat_id}/attributes/${nowParam.attr_id}`,
        {
          attr_name: nowParam.attr_name,
          attr_sel: nowParam.attr_sel,
          attr_vals: attrVals
        }
      )
      if (res.meta.status !== 200) {
        return this.$message({
          message: '添加可选项失败',
          type: 'error',
          duration: 1500
        })
      }
    },
    // 点击 添加 可选项按钮的回调
    showInput() {
      // 显示输入框，隐藏按钮
      this.inputVisible = true

      // 输入框 自动获得焦点
      // this.$nextTick()表示页面元素渲染完毕再做处理
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /** 参数可选项2 */

    /** 删除参数实现1 */
    async delParams(attrId) {
      const cfm = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (cfm === 'confirm') {
        const { data: res } = await this.$http.delete(
          `categories/${this.catId}/attributes/${attrId}`
        )

        if (res.meta.status !== 200) {
          return this.$message({
            message: '删除参数失败',
            type: 'error',
            duration: 1000
          })
        }

        // 刷新页面
        this.getParamsByCate()
        // 提示
        this.$message({
          message: '删除参数成功',
          type: 'success',
          duration: 1000
        })
      }
    },
    /** 删除参数实现2 */

    /** 修改参数弹框/form表单部分1 */
    // 展示弹框
    // @param info 被修改的参数信息
    async showEditDialog(info) {
      // 被修改参数对象复制一份 给到修改对象
      this.editForm = _.cloneDeep(info)
      // 展示
      this.editDialogVisible = true
    },
    // 关闭弹框
    editDialogclosed() {},
    // 收集数据存储
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `categories/${this.editForm.cat_id}/attributes/${
              this.editForm.attr_id
            }`,
            {
              attr_name: this.editForm.attr_name,
              attr_sel: this.activeName
            }
          )

          if (res.meta.status !== 200) {
            return this.$message({
              message: '修改参数失败',
              type: 'error',
              duration: 1000
            })
          }

          // 刷新
          this.getParamsByCate()
          // 关闭弹框
          this.editDialogVisible = false
          // 提示
          this.$message({
            message: '添加参数成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    /** 修改参数弹框/form表单部分2 */

    /** 添加参数弹框/form表单部分1 */
    // 关闭弹框
    addDialogclosed() {
      // 初始化form表单
      this.$refs.addFormRef.resetFields()
      // 关闭弹层
      this.addDialogVisible = false
    },
    // 添加参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(
            `categories/${this.catId}/attributes`,
            {
              attr_name: this.addForm.attr_name,
              attr_sel: this.activeName
            }
          )
          if (res.meta.status !== 201) {
            return this.$message({
              message: '添加参数失败',
              type: 'error',
              duration: 1000
            })
          }
          // 刷新参数信息
          this.getParamsByCate()
          // 关闭弹框
          this.addDialogVisible = false
          // 提示
          this.$message({
            message: '添加参数成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    /** 添加参数弹框/form表单部分2 */

    // 鼠标点击tab标签事件
    handleClick(tab, event) {
      if (!this.catId) return null
      // 获取 动态参数 或 静态属性
      this.getParamsByCate()
    },
    // 鼠标滑过三级分类的回调处理
    handleChange() {
      if (this.selectedCategories.length < 3) {
        // 重置级联三级分类
        this.selectedCategories = []
        // 清空 动态参数 、单选属性 数据
        this.manyTableData = []
        this.onlyTableData = []
      } else {
        // 获取 动态参数 或 静态属性
        this.getParamsByCate()
      }
    },
    // 根据 第三级分类 获取对应的 动态参数 或 静态属性
    async getParamsByCate() {
      // 根据第三级级别分类获取对应的 动态参数 或 单选属性
      const { data: res } = await this.$http.get(
        `categories/${this.catId}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取分类参数失败',
          type: 'error',
          duration: 1000
        })
      }

      // 把每个参数的 可选项 通过空格分割，变为数组再赋予回来
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      // console.log(res.data)

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 获得供选取的分类信息
    async getCategoriesList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }
      })

      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取三级分类失败',
          type: 'error',
          duration: 1000
        })
      }

      // console.log(res.data)
      this.categoriesList = res.data
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 15px;
}
.el-tag {
  margin: 10px 5px;
}
.input-new-tag {
  width: 110px;
}
</style>
